import React, { useState } from "react";
import { Button, Upload, message, Popconfirm, Space, Progress, Flex } from "antd";
import { useTranslation } from 'react-i18next';
import { UploadOutlined, DeleteOutlined, StarOutlined } from '@ant-design/icons';
import { apiBigSimulationUploadCheck, apiBigSimulationUploadChunk } from '../../../services/bigSimulationFile/request';
import DeleteConfirm from '../DeleteConfirm';
import _ from 'lodash';
import './index.scss';
import SparkMD5 from "spark-md5";

const BigFileUpload = ({
  // 上传按钮文案
  btnText,
  // 附件类型
  acceptType,
  // 上传至哪个Module
  // uploadModule,
  // 上传至哪个Module的具体记录
  // uploadName,
  // 上传或删除更新
  uploadUpdateFn,
  // 是否disabled
  disabled,
  // fileList
  fileListData,
  bigFileProductId = '2c0bb6c2-cf0a-ef2d-68d5-7bdbe4e9d2b6',
}) => {
  const CHUNK_SIZE = 1024 * 1024 * 10; // 分片大小
  const { t } = useTranslation();
  const [fileList, setFileList] = useState(fileListData || []);
  const [uploadFileList, setUploadFileList] = useState();
  const [uploadSpeedTotal, setUploadSpeedTotal] = useState();
  const [parsePercentage, setParsePercentage] = useState();
  const [chunkTotal, setChunkTotal] = useState(0);
  const [chunkIndex, setChunkIndex] = useState(0);
  const [uploadPercentage, setUploadPercentage] = useState(0);
  const { TYPE, VERIFIED } = acceptType;
  const acceptText = TYPE?.join(',');

  const beforeUpload = (file) => {
    return false;
  };
  const uploadChange = async (file) => {
    if (file?.file?.status !== 'removed') {
      const type = file?.file?.type || file?.file?.name?.split('.')?.pop()?.toLowerCase();
      const isValidType = VERIFIED?.includes(type);
      console.log(isValidType);
      if (!isValidType && VERIFIED?.length !== 0) {
        message.error(t('common.uploadTips', { type: TYPE }));
        return false;
      };
      let uploadFile = {};
      uploadFile.name = file?.file?.name;
      uploadFile.size = file?.file?.size;
      // uploadFile.parsePercentage = 0;
      // uploadFile.uploadPercentage = 0;
      uploadFile.file = file?.file;
      uploadFile.uploadingStop = false;
      // 计算md5
      const md5 = await getFilesSparkMd5(file, uploadFile);
      uploadFile.md5 = md5;
      const md5CheckResult = await apiBigSimulationUploadCheck({ bigFileProductId: bigFileProductId, md5: md5 });  //上传服务器检查，以确认是否秒传
      if (md5CheckResult?.data?.code == 200) {
        if (!md5CheckResult?.data?.data?.isUploaded) {
          uploadChunk(file, 1, uploadFile);
        } else if (md5CheckResult?.data?.data?.isUploaded) {
          message.success(t('common.secondsUplodsuccessful'));
          setUploadPercentage(100);
          const fileList = {
            name: file?.file?.name,
            status: 'done',
            url: file?.file?.name,
            md5: uploadFile.md5,
          };
          uploadUpdateFn(fileList);
          setFileList([fileList]);
        }
      }
    };
  };
  // 计算文件MD5的函数
  const getFilesSparkMd5 = (file) => {
    return new Promise((resolve, reject) => {
      let currentPosition = 0; // 当前读取位置
      const fileReader = new FileReader();
      const spark = new SparkMD5.ArrayBuffer();
      // 逐块读取文件内容并计算MD5
      const processChunk = (chunk) => {
        return new Promise((resolve, reject) => {
          spark.append(chunk);
          currentPosition += chunk.byteLength;
          resolve();
        });
      };
      // 读取下一个块
      const loadNextChunk = () => {
        const fileSlice = file?.file?.slice(
          currentPosition,
          currentPosition + CHUNK_SIZE
        );
        fileReader.readAsArrayBuffer(fileSlice);
      };
      // file  Reader onload
      fileReader.onload = (e) => {
        const chunk = e.target.result;
        if (chunk) {
          processChunk(chunk).then(() => {
            if (currentPosition < file?.file?.size) {
              loadNextChunk();
            } else {
              resolve(spark.end());
            }
          });
        }
        spark.append(e.target.result);
        let md5 = spark.end();
        resolve(md5);
      };
      // file  Reader onerror
      fileReader.onerror = (err) => {
        reject(err.target.error);
      };
      // 开始读取第一个块
      loadNextChunk();
    });
  };
  const uploadChunk = (file, index, uploadFile) => {
    const chunkTotal = Math.ceil(file?.file.size / CHUNK_SIZE);
    setChunkTotal(chunkTotal);
    setChunkIndex(index * 1 - 1);
    setUploadPercentage(Math.ceil(((index * 1 - 1) / chunkTotal * 100)));
    // 判断切片是否上传完成
    if (index <= chunkTotal) {
      const startTime = new Date().valueOf();
      const params = new FormData();
      const start = (index - 1) * CHUNK_SIZE;
      const end = index * CHUNK_SIZE >= file?.file?.size ? file?.file?.size : index * CHUNK_SIZE;
      const chunk = file?.file?.slice(start, end);
      params.append("file", chunk);
      params.append("currentChunk", index);
      params.append("chunkTotal", chunkTotal);
      params.append("chunkSize", CHUNK_SIZE);
      params.append("md5", uploadFile.md5);
      params.append("fileTotalSize", file?.file?.size);
      params.append("fileName", file?.file?.name);
      params.append("bigFileProductId", bigFileProductId);
      apiBigSimulationUploadChunk(params).then((res) => {
        if (res?.data?.code === 200) {
          const endTime = new Date().valueOf();
          const timeDif = (endTime - startTime) / 1000;
          // console.log("上传文件大小",formatSize(CHUNK_SIZE));
          console.log("耗时", timeDif);
          if (index == chunkTotal) {
            // emitter.emit("reloadFileList");
            // console.log(uploadFile.uploadPercentage);
          };
          uploadChunk(file, index + 1, uploadFile);
        }
      });
    } else {
      const fileList = {
        name: file?.file?.name,
        status: 'done',
        url: file?.file?.name,
        md5: uploadFile.md5,
      };
      uploadUpdateFn(fileList);
      setFileList([fileList]);
    }
  };
  const removeChange = (file) => {
    DeleteConfirm({
      t,
      title: t('common.deleteFileMsg'),
      onOk () {

      }
    });
  };
  return (
    <>
      <Upload
        className='upload-big-file-wrap'
        maxCount={1}
        disabled={disabled}
        accept={acceptText}
        beforeUpload={beforeUpload}
        onChange={(e) => uploadChange(e)}
        onRemove={(e) => removeChange(e)}
        fileList={fileList}
      >

        <Flex align='center' style={{ marginTop: '10px' }}>
          <Button disabled={disabled} icon={<UploadOutlined />} style={{ marginRight: '20px' }}>{btnText}</Button>
          {
            uploadPercentage > 0 &&
            <>
              <div>{t('common.progress')}: </div>
              <Progress percent={uploadPercentage} size="small" style={{ width: '50%', marginLeft: '10px' }} />
            </>
          }
        </Flex>
      </Upload>
    </>
  )
};

export default BigFileUpload;